/**
 * 登录场景UI类;
 */
import uiPanel from "./../lib/UiPanel";
const { ccclass, property } = cc._decorator;
var verificationCodeLength = 4;
@ccclass
export default class login extends uiPanel {

	@property(cc.Prefab)
	hotUpdatePrefab: cc.Prefab = null;

	@property(cc.Node)
	hotUpdateRoot: cc.Node = null;

	@property(cc.Label)
	curVersion: cc.Label = null;



	@property(cc.Button)
	btn_selectLogin: cc.Button = null
	@property(cc.Button)
	btn_register: cc.Button = null


	_timer_handle: any = null;
	countdown: number = 0;
	hotUpdateUI = null;

	eventCustomChooseServerEnd = null;
	eventCustomHotUpError = null;
	eventCustomentergamefail;

	//--------------------login new-------------------------------
	private lab_code: cc.Label = null
	private lab_loginType: cc.Label = null
	private loginType: number = 0
	private curPhoneNumnber: cc.EditBox = null

	private isClickkRegister: boolean = false
	private isClickLogin: boolean = false


	private loginTypeDesc: { [key: string]: any }[]
		= []


	onLoad() {
		cc.log("enter Login scene onLoad-----------");
		cc.vv.sceneName = "Login";
		cc.vv.Login = this;
		cc.vv.GLDefine.evenOpenGift = false;
		this.curVersion.node.active = false;

		var node = cc.instantiate(this.hotUpdatePrefab);
		node.parent = this.hotUpdateRoot;
		this.hotUpdateRoot.active = false;

		//
		// this.hotUpdateUI = node.getComponent("HotUpdateUI");
		// cc.vv.hotUpdate.init();
		// cc.vv.hotUpdate.getLocalVersion();
		// cc.vv.GLUtils.prohibitDoubleBtnClick();
		cc.vv.audioUtil.playMusic("HallDWC/hall/music/login");
	}

	private initBtnEvent(): void {
		this.btn_selectLogin.node.on(cc.Node.EventType.TOUCH_END, this.onClickLogin, this)
		this.btn_register.node.on(cc.Node.EventType.TOUCH_END, this.onClickRegister, this)
	}

	onEnable() {
		this.eventCustomHotUpError = cc.vv.eventCustom.on("hotUpError", this.hotUpError.bind(this), this.node);
		this.eventCustomChooseServerEnd = cc.vv.eventCustom.on("chooseServerEnd", this.chooseServerEnd.bind(this), this.node);
		this.eventCustomentergamefail = cc.vv.eventCustom.on("entergamefail", this.entergamefail.bind(this), this.node);
		if (cc.sys.os == cc.sys.OS_ANDROID) {
			setTimeout(() => {
				jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "removeImgView", "()V");
			}, 1500);
		}
		this.initBtnEvent()
	}
	onDisable() {
		if (typeof this.eventCustomHotUpError != "undefined") {
			cc.vv.eventCustom.off("hotUpError", this.eventCustomHotUpError);
			this.eventCustomHotUpError = undefined;
		}

		if (typeof this.eventCustomChooseServerEnd != "undefined") {
			cc.vv.eventCustom.off("chooseServerEnd", this.eventCustomChooseServerEnd);
			this.eventCustomChooseServerEnd = undefined;
		}

		if (typeof this.eventCustomentergamefail != "undefined") {
			cc.vv.eventCustom.off("entergamefail", this.eventCustomentergamefail);
			this.eventCustomentergamefail = undefined;
		}
		this.btn_selectLogin.node.off(cc.Node.EventType.TOUCH_END, this.onClickSelectLogin, this)
		//this.btn_return.node.off(cc.Node.EventType.TOUCH_END, this.onClickReturn, this)
		this.btn_register.node.off(cc.Node.EventType.TOUCH_END, this.onClickRegister, this)
		// this.btn_getCode.node.off(cc.Node.EventType.TOUCH_END, this.onClickGetCode, this)
		// this.btn_login.node.off(cc.Node.EventType.TOUCH_END, this.onClickLogin, this)
		// this.btn_changeType.node.off(cc.Node.EventType.TOUCH_END, this.onClickChangeType, this)
		this.clearTimerHandler()
	}
	onDestroy() {
		cc.vv.Login = null;
		cc.vv.GLConfig.isInit = true;
	}
	clearTimerHandler() {
		// if (this._timer_handle) {
		// 	clearInterval(this._timer_handle);
		// 	this._timer_handle = null;
		// }
		// this.lab_code.node.color = new cc.Color().fromHEX('#1289FF');
		// this.lab_code.string = `获取验证码`
	}

	init(args) {
		cc.vv.MarqueeDataModel.close();
		this.reset()
		if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS)
			this.getCDNtoServer();
		else
			this.hotUpdate();

	}
	reset() {
		// this.isClickkRegister = false
		// this.changeParentNodeType(true)
		// this.changeBtnEnable(this.btn_register, true)
		// this.resetLogin()
	}

	resetLogin() {
		this.isClickLogin = false
		// this.changeBtnEnable(this.btn_login, true)
	}

	hotUpdate() {
		this.hotEnd();
		return;
		var _updateFaild = cc.vv.GLUtils.getUpdateFaild();
		if (_updateFaild) {
			cc.vv.hotUpdate.removeHotUpdateTempDir();
		}
		if (cc.sys.os != cc.sys.OS_IOS) {
			cc.vv.UIMgr.open(cc.vv.GLConfig.waiting_path, null, null, "版本检测中...");
		}
		if (!cc.vv.GLConfig.hotUpdateURL) {
			cc.vv.GLNet.getCdnUrl(function () {
				if (cc.sys.os == cc.sys.OS_IOS && !cc.vv.GLConfig.getIOScheckhot) {
					if (cc.vv.GLConfig.hotupd) {
						cc.vv.hotUpdate.checkUpdate();
						return;
					} else {
						this.hotEnd();
						return;
					}
				} else {
					cc.vv.hotUpdate.checkUpdate();
				}
			}.bind(this));
		} else {
			if (cc.sys.os == cc.sys.OS_IOS && !cc.vv.GLConfig.getIOScheckhot) {
				if (cc.vv.GLConfig.hotupd) {
					cc.vv.hotUpdate.checkUpdate();
					return;
				} else {
					this.hotEnd();
					return;
				}
			} else {
				cc.vv.hotUpdate.checkUpdate();
			}
		}
	}

	hotUpError(args) {
		var errCode = args[0];
		console.log("____errCode = " + errCode);
		cc.vv.UIMgr.close(cc.vv.GLConfig.waiting_path, cc.vv.UIMgr.closeType.hide);

		switch (errCode) {
			case cc.vv.hotUpdate.errorCode.NEED_UPDATE: //有热更版本
				this.hotUpdateRoot.active = true;
				this.hotUpdateUI.progressRoot.active = false;

				var _version1 = args[1];
				var _version2 = args[2];

				var str = "资源文件有更新，必须更新后才能继续游戏";
				var okEvent = function () {
					this.hotUpdateUI.progressBar.progress = 0;
					this.hotUpdateUI.progressRoot.active = true;
					this.hotUpdateUI.progressBar.node.active = true;
					cc.vv.hotUpdate.hotUpdate();
					this.hotUpdateUI.showVersion(_version1, _version2);
				}.bind(this);
				var canleEvent = function () {
					cc.game.end();
				}.bind(this);
				//this.hotUpdateUI.showPopup(canleEvent, okEvent, str);
				cc.vv.GLUtils.showAlert1(str, okEvent, canleEvent)
				break;
			case cc.vv.hotUpdate.errorCode.NEED_INSTALL: //需要重新下载安装
				var str = "需要重新下载安装才能继续游戏";
				this.downLoadApkOrIpa(str);
				break;
			case cc.vv.hotUpdate.errorCode.ERROR_NO_LOCAL_MANIFEST: //本地没有配置文件
				var str = "没有本地版本文件，请重新下载";
				this.downLoadApkOrIpa(str);

				break;
			case cc.vv.hotUpdate.errorCode.FAIL_DOWMLOAD_MANIFEST: //下载配置失败
				var str = "下载失败，请重试";
				this.reHotUpdate(str);
				break;
			case cc.vv.hotUpdate.errorCode.ALREADY_UP_TO_DATE: //已经更新
				this.hotEnd();
				break;
			case cc.vv.hotUpdate.errorCode.UPDATE_PROGRESSION: // 更新中
				var percent = args[1];
				var totalSize = args[2];
				console.log("_______args = " + args);
				console.log("_____persent = " + percent);
				console.log("_____totalSize = " + totalSize);

				this.hotUpdateUI.updateProgress(3, percent, totalSize);

				break;
			case cc.vv.hotUpdate.errorCode.UPDATE_FINISHED: //更新完成
				break;
			case cc.vv.hotUpdate.errorCode.ERROR_UPDATING: // 下载失败
				break;
			case cc.vv.hotUpdate.errorCode.UPDATE_FAILED: //更新失败111
				var msg = args[1];
				var str = "更新失败，请重试";
				if (msg) {
					str = "更新文件:" + msg + "失败"; //"更新失败，请重试";
				}
				//todo 存储错误标记
				cc.vv.GLUtils.saveUpdateFaild(true);

				this.hotUpdateRoot.active = true;
				this.hotUpdateUI.progressRoot.active = false;

				var okEvent = function () {
					this.hotUpdateUI.progressRoot.active = true;
					this.hotUpdateUI.progressBar.node.active = true;

					cc.vv.hotUpdate.retry();
				}.bind(this);
				var canleEvent = function () {
					cc.game.end();
				}.bind(this);
				//this.hotUpdateUI.showPopup(canleEvent, okEvent, str);
				cc.vv.GLUtils.showAlert1(str, okEvent, canleEvent, null, "", "重试", "退出");

				break;
			case cc.vv.hotUpdate.errorCode.ERROR_DECOMPRESS: //解压失败111
				break;
			case cc.vv.hotUpdate.errorCode.ERROR_OTHER:
				this.hotEnd();
				break;
		}
	}

	reHotUpdate(str) {
		console.log("_____reHotUpdate");
		var str = str || "";

		this.hotUpdateRoot.active = true;
		this.hotUpdateUI.progressRoot.active = false;

		var okEvent = function () {
			this.hotUpdate();
		}.bind(this);
		var canleEvent = function () {
			cc.game.end();
		}.bind(this);
		//HotUpdate.removeHotUpdateDir();
		console.log("reHotUpdate");
		//this.hotUpdateUI.showPopup(canleEvent, okEvent, str);
		cc.vv.GLUtils.showAlert1(str, okEvent, canleEvent, null, "", "重试", "退出");
	}

	downLoadApkOrIpa(str) {
		this.hotUpdateRoot.active = true;
		this.hotUpdateUI.progressRoot.active = false;

		var url = "";
		if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
			url = cc.vv.GLConfig.getGM_url();
		} else if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
			url = cc.vv.GLConfig.getGM_url();
		}
		console.log("______openurl11 = " + url);
		var okEvent = function () {
			cc.vv.GLSDKMgr.openURL(url);
			cc.vv.GLUtils.clearUserInfo();
			cc.vv.hotUpdate.removeHotUpdateDir();
			//cc.vv.audioUtil.pauseAll();
			cc.game.end();
		}.bind(this);
		var canleEvent = function () {
			cc.game.end();
		}.bind(this);

		//this.hotUpdateUI.showPopup(canleEvent, okEvent, str);
		cc.vv.GLUtils.showAlert1(str, okEvent, canleEvent)
	}

	hotEnd() {
		this.hotUpdateRoot.active = false;
		cc.vv.GLUtils.saveUpdateFaild(false);
		//
		this.setChanel();
		this.showLogin();
	}

	setChanel() {
		var agentID = cc.vv.GLSDKMgr.getClipboard();
		//test
		// agentID = { "rid": "2000016" };//{ "code": "1234", "rid": "2000016" };
		// agentID = JSON.stringify(agentID);
		cc.vv.platform.setChanel(agentID);
	}

	//显示登录
	showLogin() {
		//this.showVersion();
		if (cc.vv.GLConfig.game_debug_state == cc.vv.GLDefine.EDebugType.DEBUG) {
			cc.vv.UIMgr.open(cc.vv.GLConfig.serverPanel_path);
		} else {
			this.reallogin();
		}
	}

	private getCDNtoServer(): void {
		if (!cc.vv.GLConfig.isIosExaminePackage) {
			this.hotUpdate();
		} else {
			//通过cdn获取登录服地址
			let _version = cc.vv.GLConfig.getLocalVersion() + "";
			let params = {
				cmd: "getRealUrl",
				msg: {},
				version: _version
			};
			cc.vv.GLNet.netPost(params, this.httpCallBack.bind(this));
		}
	}

	private httpCallBack(data: any): void {
		if (data) {
			var _data = JSON.parse(data);
			if (_data.err) {//获取失败
				//提示错误
				cc.vv.GLUtils.showAlert1("连接服务器失败！", function () {
					cc.game.end()
				}.bind(this), null);
			} else {
				//设置登录服地址
				let loginServerInfo = {
					platform_ip: _data.res.server,
					platform_port: _data.res.port,
					versionType: 0
				}
				cc.vv.GLNetDataModel.setPlatformCfg(loginServerInfo)
				//热更检测
				this.hotUpdate();
			}
		}
	}
	//选择服务器
	chooseServerEnd() {
		this.reallogin();
	}
	reallogin() {
		this.checkIsClearUserData()
		let accountInfo = cc.vv.GLUtils.getAccountInfo()
		if (accountInfo && accountInfo.logintoken) { //  如果有账号，直接登录
			cc.vv.eventCustom.emit('initSelfData');
			cc.vv.GLNet.loginEnterGame()
		}
	}

	private checkIsClearUserData(): void {
		let accInfo = cc.vv.GLUtils.getAccountInfo()
		if (accInfo) {
			let curLoginArss = cc.vv.GLNetDataModel.getPlatformCfg().platform_ip
			if (accInfo.platform_ip != undefined && curLoginArss != accInfo.platform_ip) {
				cc.vv.GLUtils.clearAccountInfo()
			}
		}
	}


	//
	changeBtnEnable(target: cc.Button, enable: Boolean) {
	}

	/**
	 * 
	 * @param status true:注册 false:登录
	 */
	private changeParentNodeType(status: boolean): void {
		// this.nodeRegister.active = status
		// this.nodeLogin.active = !status
		this.clearTimerHandler();
		if (status) {
			// this.inputPHoneNumber.string = ""
			// this.inputCode.string = ""
			// this.inputPd.string = ""
			// this.inputPdNotarize.string = ""
			// this.curPhoneNumnber = this.inputPHoneNumber
		} else {
			// this.inputLoginphoneNumber.string = ""
			// this.inputLoginCode.string = ""
			// this.curPhoneNumnber = this.inputLoginphoneNumber
		}
	}

	private onClickSelectLogin(): void {
		this.loginType = 0
		this.changeParentNodeType(false)
		this.fillData()
		let tempData = this.loginTypeDesc[this.loginType]
		this.lab_loginType.string = tempData.name
		// this.btn_getCode.node.active = this.loginType == 0
		// this.inputLoginCode.textLabel.node.width = tempData.with
		// this.inputLoginCode.placeholderLabel.node.width = tempData.with
		// this.inputLoginCode.placeholderLabel.string = tempData.inputDes
	}

	private onClickReturn(): void {
		this.changeParentNodeType(true)
	}


	//注册
	private onClickRegister(): void {
		cc.vv.audioUtil.playSound("/Hall/sound/button_onclicked");
		cc.vv.UIMgr.open(cc.vv.GLConfig.dwc_RegisterPanel_path, null, null);
	}

	//
	private onClickWxLogin(){
		cc.vv.GLSDKMgr.login(cc.vv.GLDefine.EAuthType.WECHAT)
	}
	//打开手机登陆面板
	private onClickPhoneLogin(){
		cc.vv.audioUtil.playSound("/Hall/sound/button_onclicked");
		cc.vv.UIMgr.open(cc.vv.GLConfig.dwc_PhoneLogin_path, null, null);
    }

	private onClickLogin(): void {
		cc.vv.audioUtil.playSound("/Hall/sound/button_onclicked");
		cc.vv.UIMgr.open(cc.vv.GLConfig.dwc_LoginPanel_path, null, null);
	}

	private fillData(): void {
		console.log("this.loginType===", this.loginType)
		let tempData = this.loginTypeDesc[this.loginType]
		this.lab_loginType.string = tempData.name
		// this.btn_getCode.node.active = this.loginType == 0
		// this.inputLoginCode.string = ""
		// this.inputLoginCode.maxLength = tempData.maxLen
		// this.inputLoginCode.placeholderLabel.string = tempData.inputDes
		// this.inputLoginCode.inputFlag = tempData.inFlag
		// this.inputLoginCode.inputMode = tempData.inModel
	}
	private onClickChangeType(): void {
		this.loginType = this.loginType ? 0 : 1
		this.fillData()
	}
	//获取验证码
	onClickGetCode() {
		let phNum: string = this.curPhoneNumnber.string
		if (cc.vv.GLUtils.checkPhone(phNum)) {
			var params = {
				cmd: "VerificationCode",
				msg: {
					phone: phNum
				}
			};
			cc.vv.GLNet.netPost(params, this.VerificationCodeEnd.bind(this));
		} else {
			cc.vv.GLUtils.showTips("请输入正确的电话号码！");
		}

	}

	VerificationCodeEnd(data) {
		if (data) {
			var _data = JSON.parse(data);
			if (!_data.status) {
				cc.vv.GLUtils.showTips(_data.errdesc);
				//this.huoquEnable(true, this.huoQu);
			} else {
				cc.vv.GLUtils.showTips("发送成功");
				//倒计时
				this.countdown = 60;
				this.lab_code.node.color = new cc.Color().fromHEX('#cccccc');
				this._timer_handle = setInterval(function () {
					if (this.countdown <= 0) {
						this.clearTimerHandler();
						return;
					}
					this.countdown--;
					this.lab_code.string = `重新获取(${this.countdown})`;
				}.bind(this), 1000);

			}
		} else {
		}
	}


	relogin() {
		this.reset();
	}

	entergamefail() {
		this.reset();
	}

}
